package com.xjk.controller;

import com.alibaba.fastjson.JSONObject;
import com.xjk.bean.TblUserRecord;
import com.xjk.pojo.Permission;
import com.xjk.pojo.ResultObject;
import com.xjk.pojo.ResultOverallObject;
import com.xjk.pojo.RoleObj;
import com.xjk.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xjk
 */

@Controller
@ResponseBody
public class TestController {

    @Autowired
    LoginService loginService;

    @RequestMapping("/auth/login")
    public String login(@RequestParam("username") String u, @RequestParam("password") String p,HttpSession session){
        System.out.println(u+"-----------------"+p);
        TblUserRecord login = loginService.login(u, p);
        login.setToken(login.getUserName());
        session.setAttribute("userRecord",login);
        ResultOverallObject resultOverallObject = new ResultOverallObject(login);
        System.out.println(session.getId());
        return JSONObject.toJSONString(resultOverallObject);
    }

    @RequestMapping("/user/info")
    public String getInfo(HttpSession httpSession){
        System.out.println(httpSession.getAttribute("userRecord"));
        TblUserRecord tblUserRecord = (TblUserRecord) httpSession.getAttribute("userRecord");
        // 获取权限模块信息
        String[] permissionIds = tblUserRecord.getTblRole().getRolePrivileges().split("-");
        RoleObj roleObj = new RoleObj();
        List<Permission> permissions = new ArrayList<>();
        for (String permissionId : permissionIds) {
            permissions.add(new Permission(permissionId));
        }
        roleObj.setPermissions(permissions);
        ResultObject resultObject = new ResultObject();
        resultObject.setName(tblUserRecord.getUserName());
        resultObject.setRole(roleObj);
        System.out.println(JSONObject.toJSONString(new ResultOverallObject(resultObject)));
        return JSONObject.toJSONString(new ResultOverallObject(resultObject));
    }

    @RequestMapping("/auth/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "";
    }



}
